package com.bj58.mis.apm.client.springboot.filter;

import java.io.IOException;
import java.util.*;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bj58.mis.apm.client.boot.http.HttpRecordUtil;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.util.NestedServletException;

public class ApmClientFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest sevRequest, ServletResponse sevResponse, FilterChain chain)
			throws IOException, ServletException {
		/**
		 * if not a http request then send a error to the client
		 */
		if (sevRequest instanceof HttpServletRequest) {
			HttpServletRequest request = (HttpServletRequest) sevRequest;
			HttpServletResponse response = (HttpServletResponse) sevResponse;

			long startTime = System.currentTimeMillis();
			try {
				chain.doFilter(request, response);
				if (!request.isAsyncStarted()) {
					// Only record when async processing has finished or never been started.
					// If async was started by something further down the chain we wait
					// until the second filter invocation (but we'll be using the
					// TimingContext that was attached to the first)
					Throwable exception = (Throwable) request
							.getAttribute(DispatcherServlet.EXCEPTION_ATTRIBUTE);
					HttpRecordUtil.recordHttpAccessLog(request, response, startTime, exception);
				}
			}
			catch (NestedServletException ex) {
				response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
				HttpRecordUtil.recordHttpAccessLog(request, response, startTime, ex.getCause());
				throw ex;
			}
		}
	}




	@Override
	public void destroy() {
	}


}
